<template>
  <div class="dept">
    <el-upload
      id="upimg"
      v-show="false"
      class="upload-demo"
      :action="imgUploadUrl"
      :on-success="handleSuccess"
      :headers="config"
      multiple
    >
      <el-button size="small" type="primary">点击上传</el-button>
    </el-upload>

    <quill-editor v-model="dataForm.content" :options="editorOption" ref="QuillEditor"></quill-editor>
  </div>
</template>
<script>
// 富文本编辑器工具栏配置，因为涉及到富文本编辑器以外的组件调用，所以在这里我们需要重新自定义一下富文本编辑器的工具栏
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"], // toggled buttons
  ["blockquote", "code-block"],

  [
    {
      header: 1,
    },
    {
      header: 2,
    },
  ], // custom button values
  [
    {
      list: "ordered",
    },
    {
      list: "bullet",
    },
  ],
  [
    {
      script: "sub",
    },
    {
      script: "super",
    },
  ], // superscript/subscript
  [
    {
      indent: "-1",
    },
    {
      indent: "+1",
    },
  ], // outdent/indent
  [
    {
      direction: "rtl",
    },
  ], // text direction

  [
    {
      size: ["small", false, "large", "huge"],
    },
  ], // custom dropdown
  [
    {
      header: [1, 2, 3, 4, 5, 6, false],
    },
  ],

  [
    {
      color: [],
    },
    {
      background: [],
    },
  ], // dropdown with defaults from theme
  [
    {
      font: [],
    },
  ],
  [
    {
      align: [],
    },
  ],
  ["link", "image", "video"],
  ["clean"], // remove formatting button
];
export default {
  name: "quill",
  created() {
    this.token = this.$cookie.get("token");
  },
  computed: {
    config() {
      return { token: this.token };
    },
  },

  data() {
    return {
      imgUploadUrl: "http://localhost:8080/renren-fast/uploadImgFile",
      token: "",
      // 富文本编辑器工具栏
      editorOption: {
        modules: {
          toolbar: {
            container: toolbarOptions, // 工具栏
            handlers: {
              image: function (value) {
                if (value) {
                  // 调用element的图片上传组件
                  // （这里是用的原生js的选择dom方法）
                  document.querySelector("#upimg button").click();
                } else {
                  this.quill.format("image", false);
                }
              },
            },
          },
        },
      },
    };
  },
  methods: {
    handleSuccess(res) {
      // 获取富文本组件实例
      console.log(res);
      let quill = this.$refs.QuillEditor.quill;
      if (res.code == 0) {
        // 如果上传成功
        // 获取光标所在位置
        let length = quill.getSelection().index;
        // 插入图片，res为服务器返回的图片链接地址
        quill.insertEmbed(length, "image", res.url);
        // 调整光标到最后
        quill.setSelection(length + 1);
      } else {
        // 提示信息
        this.$message.error("图片插入失败");
      }
    },
  },
};
</script>
<style lang="scss">
</style>
